﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Formatting;

using Seven.Tools.Helper;
using Seven.Tools.Extension;
using Seven.Web.Http;

namespace Seven.Service.Security
{
    public static class ServicePool
    {
        /// <summary>
        /// 服务池url
        /// </summary>
        public static string ServerPoolUrl { get; set; }
        /// <summary>
        /// SignalR服务的控制器名称
        /// </summary>
        public static string SignalRServiceController { get; set; }
        /// <summary>
        /// Member服务的控制器名称
        /// </summary>
        public static string MemberServiceController { get; set; }

        public static string ServerPoolExceptionInfo = "访问服务池出现异常！";

        static ServicePool()
        {
            var config = new SiteCore();
            ServerPoolUrl = config.SignalRServiceUrl;
            SignalRServiceController = "";
            MemberServiceController = "MemberService";
        }

        /// <summary>
        /// Member服务的调用路径地址，注意：此处不包含服务池url
        /// </summary>
        public static string MemberServiceUrl { get { return "api/" + MemberServiceController + "/"; } }

        /// <summary>
        /// 检验服务池Url
        /// </summary>
        private static void CheckBaseUrl()
        {
            if (string.IsNullOrWhiteSpace(ServerPoolUrl))
            {
                throw new Exception("服务池地址未设置！请在Webconfig中设置<ServerPoolUrl>的具体值！");
            }
        }

        /// <summary>
        /// 检验服务池配置项
        /// </summary>
        /// <param name="type">1表示检验用户服务相关的配置项；2表示检验推送服务相关的配置项</param>
        private static void CheckConfig(int type)
        {
            CheckBaseUrl();
            if (type == 1 && string.IsNullOrWhiteSpace(MemberServiceController))
            {
                throw new Exception("用户服务控制器名称未设置！请联系管理员！");
            }
            else if (type == 2 && string.IsNullOrWhiteSpace(MemberServiceController))
            {
                throw new Exception("推送服务控制器名称未设置！请联系管理员！");
            }
        }

        /// <summary>
        /// HttpClient初始化
        /// </summary>
        /// <returns></returns>
        private static HttpClient ClientInit()
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(ServerPoolUrl);
            // 为JSON格式添加一个Accept报头
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            return client;
        }

        /// <summary>
        /// 常规登录
        /// </summary>
        /// <param name="model">登录数据模型</param>
        /// <param name="resultModel">输出参数，登录成功后获得的用户信息模型</param>
        /// <returns></returns>
        public static OperationResult NormalLogin(LoginModel model, ref UserInfoModel resultModel)
        {
            CheckConfig(1);
            OperationResult result;
            try
            {
                var param = new { Account = model.UserName, Password = model.Password };
                HttpResponseMessage response = ClientInit().PostAsJsonAsync(MemberServiceUrl + "NormalLogin", param).Result;

                if (response.IsSuccessStatusCode)
                {
                    var info = response.Content.ReadContentAsString();
                    LoginResultModel obj = Seven.Tools.Helper.JsonHelper.DeserializeObject<LoginResultModel>(info);
                    result = new OperationResult(obj.Success, obj.FailMessage);
                    if (obj.Success) { resultModel = obj.Data; }
                }
                else
                {
                    result = new OperationResult (false, "失败编码：" + response.StatusCode + "，信息：" + response.ReasonPhrase );
                }
            }
            catch (Exception e)
            {
                throw new Exception(ServerPoolExceptionInfo + "异常信息：" + e.Message);
            }

            return result;
        }

        /// <summary>
        /// 常规注销退出
        /// </summary>
        /// <param name="model">已登录数据模型</param>
        /// <returns></returns>
        public static OperationResult NormalLogout(LoginedModel model)
        {
            CheckConfig(1);
            OperationResult result;
            try
            {
                var param = new { Account = model.Account, Token = model.Token.ToString() };
                HttpResponseMessage response = ClientInit().PostAsJsonAsync(MemberServiceUrl + "NormalLogout/" + "?token=" + param.Token, param).Result;

                if (response.IsSuccessStatusCode)
                {
                    var info = response.Content.ReadContentAsString();
                    ResultModel obj = Seven.Tools.Helper.JsonHelper.DeserializeObject<ResultModel>(info);
                    result = new OperationResult(obj.Success, obj.FailMessage);
                }
                else
                {
                    result = new OperationResult(false, "失败编码：" + response.StatusCode + "，信息：" + response.ReasonPhrase);
                }
            }
            catch (Exception e)
            {
                throw new Exception(ServerPoolExceptionInfo + "异常信息：" + e.Message);
            }

            return result;
        }

        /// <summary>
        /// 检查用户登录状态是否有效
        /// </summary>
        /// <param name="model">已登录数据模型</param>
        /// <returns></returns>
        public static bool CheckOnline(LoginedModel model)
        {
            CheckConfig(1);
            bool result = false;
            try
            {
                var param = new { Account = model.Account, Token = model.Token.ToString() };
                HttpResponseMessage response = ClientInit().PostAsJsonAsync(MemberServiceUrl + "CheckLoginState/" + "?account=" + model.Account, param).Result;

                if (response.IsSuccessStatusCode)
                {
                    var info = response.Content.ReadContentAsString();
                    result = info.ToLower() == "true";
                }
                else if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                {
                    return false;
                }
                else
                {
                    throw new Exception("失败编码：" + response.StatusCode + "，信息：" + response.ReasonPhrase);
                }
            }
            catch (Exception e)
            { throw new Exception(ServerPoolExceptionInfo + "异常信息：" + e.Message); }

            return result;
        }

        /// <summary>
        /// 刷新用户身份标识的最后一次请求到服务器的时间
        /// </summary>
        /// <param name="model">已登录数据模型</param>
        /// <returns>返回请求之间所允许的时间（以分钟为单位）</returns>
        public static int UpdateTokenLastRequestTime(LoginedModel model)
        {
            CheckConfig(1);
            int result = 20;
            try
            {
                var param = new { Account = model.Account, Token = model.Token.ToString() };
                HttpResponseMessage response = ClientInit().PostAsJsonAsync(MemberServiceUrl + "UpdateState/" + "?account=" + model.Account, param).Result;

                if (response.IsSuccessStatusCode)
                {
                    var info = response.Content.ReadContentAsString();
                    result = info.ToInt(20);
                }
                else
                {
                    throw new Exception("失败编码：" + response.StatusCode + "，信息：" + response.ReasonPhrase);
                }
            }
            catch (Exception e)
            { throw new Exception(ServerPoolExceptionInfo + "异常信息：" + e.Message); }

            return result;
        }
    }
}
